package postgres

import (
	"auth/model"
	"auth/model/entity"
)

var Job = &job{}

type job struct{}

func (a *job) Create(m *entity.Job) (int64, error) {
	err := db.Create(m).Error
	return m.JobId, err
}

func (a *job) Find(id int64) (*entity.Job, error) {
	e := &entity.Job{}
	err := db.Model(&entity.Job{}).Find(&e, id).Error
	return e, err
}

func (a *job) FindByParameter(in *model.JobInfo) (*entity.Job, error) {
	var (
		err    error
		q      = db.Model(&entity.Job{})
		entity entity.Job
	)
	if in.JobName != "" {
		q = q.Where("job_name = ?", in.JobName)
	}
	err = q.First(&entity).Error
	return &entity, err
}

func (a *job) FindByUserId(userId int64) ([]*entity.Job, error) {
	var (
		err     error
		entitys []*entity.Job
	)
	db.Where(" job_id in (select job_id from user_jobs where user_id = ? )", userId).
		Find(&entitys)
	return entitys, err
}

func (a *job) IsExistJobName(notEqId int64, jobName string) error {
	var (
		err    error
		q      = db.Model(&entity.Job{})
		entity entity.Job
	)
	if jobName != "" {
		q = q.Where("job_name = ?", jobName)
	}
	if notEqId > 0 {
		q = q.Where("job_id <> ?", notEqId)
	}
	err = q.First(&entity).Error
	return err
}

func (a *job) Update(id int64, dict map[string]interface{}) error {
	return db.Model(&entity.Job{}).Where("job_id = ?", id).Updates(dict).Error
}

func (a *job) Delete(id int64) error {
	return db.Delete(&entity.Job{}, id).Error
}

func (a *job) List(in *model.JobListRequest) (int, []*entity.Job, error) {
	var (
		q     = db.Model(&entity.Job{})
		err   error
		total int64
		jobs  []*entity.Job
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&jobs).Error; err != nil {
		return 0, nil, err
	}
	return int(total), jobs, nil
}
